package jlfm.lastfm.client.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import jlfm.lastfm.client.LastFmClientFaultException;
import jlfm.lastfm.client.command.LastFmCommandResult;

public class DefaultResponseParser implements LastFmResponseParser {

	public LastFmCommandResult parse(InputStream in) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			BufferedReader bin = new BufferedReader(new InputStreamReader(in,
					"UTF-8"));
			String line;
			while ((line = bin.readLine()) != null) {
				parseLine(map, line);
			}
		} catch (IOException e) {
			throw new LastFmClientFaultException(e);
		}
		return new LastFmCommandResult(map);
	}

	private void parseLine(Map<String, String> map, String line) {
		int i = line.indexOf("=");
		if (i > -1) {
			String key = line.substring(0, i).trim();
			String value = line.substring(i + 1).trim();
			map.put(key, value);
		}

	}
}
